package com.damage.purchase_dept.web;

import com.damage.common.config.CodeConfig;
import com.damage.common.dto.PurchasePlanMaker;
import com.damage.common.entity.PurchasePlan;
import com.damage.common.exception.IdentityException;
import com.damage.common.exception.IncorrectPriceException;
import com.damage.common.exception.ObsoleteException;
import com.damage.common.oa.makePurchasePlan.MakePurchaePlanWorkflowService;
import com.damage.common.object.BaseResp;
import com.damage.common.util.UserUtil;
import com.damage.common.util.Variable;
import com.damage.common.oa.makePurchasePlan.MakePurchasePlanConfig;
import com.damage.purchase_dept.oa.makePurchasePlan.ReApplyService;
import com.damage.purchase_dept.service.IPurchasePlanService;
import com.damage.purchase_dept.oa.makePurchasePlan.StartMakePurchasePlanService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/purchasePlan")
@ResponseBody
@Slf4j
public class PurchasePlanController {

    @Autowired
    private StartMakePurchasePlanService startMakePurchasePlanService;

    @Autowired
    private ReApplyService reApplyService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IPurchasePlanService purchasePlanService;

    @Autowired
    private MakePurchaePlanWorkflowService workflowService;

    @PostMapping("/start")
    public BaseResp startPurchasePlan(PurchasePlanMaker purchasePlanMaker, HttpSession session){
        try {
            User user = UserUtil.getUserFromSession(session);
            if (user == null || Strings.isNullOrEmpty(user.getId())){
                //用户未登录
                return BaseResp.error(CodeConfig.ERROR_NOT_LOGIN);
            }
            if (!user.getFirstName().equals(purchasePlanMaker.getPlanner())){
                return BaseResp.error("采购计划的制定人和登录的用户不一致！");
            }
            PurchasePlan purchasePlan = new PurchasePlan(purchasePlanMaker);
            PurchasePlan result = startMakePurchasePlanService.startMakePurchasePlan(purchasePlan);
            return BaseResp.ok(result);
        } catch (IncorrectPriceException | ObsoleteException | IdentityException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }

    @GetMapping("/list/task")
    public BaseResp taskList(HttpSession session){
        String userId = UserUtil.getUserFromSession(session).getId();
        List<PurchasePlan> planList = workflowService.findTodoTasks(userId);
        return BaseResp.ok(planList);
    }

    @GetMapping("/list/running")
    public BaseResp runnlingList(){
        List<PurchasePlan> planList = workflowService.findRunningProcessInstaces();
        return BaseResp.ok(planList);
    }

    @GetMapping("/list/finished")
    public BaseResp finishedList(){
        List<PurchasePlan> planList = workflowService.findFinishedProcessInstaces();
        return BaseResp.ok(planList);
    }

    @PostMapping("/apply/complete/{id}")
    public BaseResp completeApplyTask(@PathVariable("id")String taskId){
        try {
            taskService.complete(taskId);
            return BaseResp.ok();
        } catch (Exception e) {
            log.error("完成任务失败，任务:{}",taskId);
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }

    @PostMapping("/reApply/compelete/{id}")
    public BaseResp completeReApplyTask(@PathVariable("id")String taskId,
                                      @RequestParam(value = "purchasePlan",required = false) PurchasePlan purchasePlan,
                                      Boolean reApply ){
        try {
            if (reApply == true){
                //需要重新申请
                if (purchasePlan == null){
                    String errorMsg = "没有接收到需要重新申请的采购计划参数！";
                    log.error(errorMsg);
                    return BaseResp.error(errorMsg);
                }
                reApplyService.reApplyPurchasePlan(taskId,purchasePlan);
                log.info("重新申请采购计划！");
                return BaseResp.ok();
            }else{
                //不需要重新申请
                reApplyService.cancelApplyPurchasePlan(taskId);
                log.info("取消申请采购计划！");
                return BaseResp.ok();
            }
        } catch (Exception e) {
            log.error("完成任务失败，任务:{}",taskId);
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }


    @GetMapping("/detail/{id}")
    public BaseResp getPurchasePlanDetail(@PathVariable("id")Integer purchasePlanId){
        PurchasePlan purchasePlan = purchasePlanService.findDetailedPurchasePlanById(purchasePlanId);
        return BaseResp.ok(purchasePlan);
    }


}
